package com.dqp.cslggroup.Util;

import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.webkit.WebSettings;
import com.alibaba.fastjson.JSONObject;
import com.dqp.cslggroup.bean.Borrow;
import com.dqp.cslggroup.bean.Consumer;
import com.dqp.cslggroup.bean.scoreDetails;
import okhttp3.Cookie;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtil {
    //去（）
    public static String RemoveBrackets(String x) {
        String reStr = null;
        Pattern pattern = Pattern.compile("(?<=\\()[^\\)]+");
        Matcher matcher = pattern.matcher(x);
        while (matcher.find()) {
            reStr = matcher.group();
        }
        return reStr;
    }

    public static String replaceString(String article, String old, String now) {
        article = article.replace(old, now);
        return article;
    }


    //去数字变数组
    public static int[] SelectNumber(String x) {
        int[] a = new int[0];
        try {
            String regEx = "[^0-9]+";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(x);
            String string = m.replaceAll(" ").trim();
            String[] strArr = string.split(" ");
            int length = strArr.length;
            a = new int[length];
            StringBuffer stringBuffer = new StringBuffer();
            int i = 0;
            for (String s : strArr) {
                stringBuffer.append(s);
                a[i] = Integer.parseInt(s);
                i++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a;
    }

    //判断单双周
    public static int singleOrdouble(String string) {

        if (string.contains("(")) {
            if (RemoveBrackets(string).contains("单")) {
                return 1;
            } else if (RemoveBrackets(string).contains("双")) {
                return 0;
            }
        }
        return -1;
    }

    //判断节数
    public static int contain_js(String jc) {
        int js = 0;
        if (jc.contains("9")) {
            js = 9;
        } else if (jc.contains("1")) {
            js = 1;
        } else if (jc.contains("3")) {
            js = 3;
        } else if (jc.contains("5")) {
            js = 5;
        } else if (jc.contains("7")) {
            js = 7;
        }
        return js;
    }

    //判断星期几
    public static int contain_week(String week) {
        int xq = 0;
        if (week.contains("一")) {
            xq = 1;
        } else if (week.contains("二")) {
            xq = 2;
        } else if (week.contains("三")) {
            xq = 3;
        } else if (week.contains("四")) {
            xq = 4;
        } else if (week.contains("五")) {
            xq = 5;
        } else if (week.contains("六")) {
            xq = 6;
        } else if (week.contains("日")) {
            xq = 7;
        }
        return xq;
    }

    //提取数字
    public static String select_num(String string) {
        Pattern strp = Pattern.compile("\\d+");
        Matcher mc = strp.matcher(string);
        while (mc.find()) {
            System.out.print(" " + mc.group());
        }
        return string;
    }


    public static String select_decimal(String str) {
        // 需要取整数和小数的字符串

        // 控制正则表达式的匹配行为的参数(小数)
        Pattern p = Pattern.compile("(\\d+\\.\\d+)");
        //Matcher类的构造方法也是私有的,不能随意创建,只能通过Pattern.matcher(CharSequence input)方法得到该类的实例.
        Matcher m = p.matcher(str);
        //m.find用来判断该字符串中是否含有与"(\\d+\\.\\d+)"相匹配的子串
        if (m.find()) {
            //如果有相匹配的,则判断是否为null操作
            //group()中的参数：0表示匹配整个正则，1表示匹配第一个括号的正则,2表示匹配第二个正则,在这只有一个括号,即1和0是一样的
            str = m.group(1) == null ? "" : m.group(1);
        } else {
            //如果匹配不到小数，就进行整数匹配
            p = Pattern.compile("(\\d+)");
            m = p.matcher(str);
            if (m.find()) {
                //如果有整数相匹配
                str = m.group(1) == null ? "" : m.group(1);
            } else {
                //如果没有小数和整数相匹配,即字符串中没有整数和小数，就设为空
                str = "";
            }
        }
        return str;
    }


    //去回车
    public static String select_kcm(String string, int index) {
        String error = "";
        if (string.contains("\n")) {
            String[] idArry = string.trim().split("\n");
            return idArry[index];
        }
        return error;
    }

    // 求最大值
    public static int getMax(int[] arr) {
        int arrMax = arr[0];
        for (int i = 0; i < arr.length; i++) {
            //判断最大值
            if (arr[i] > arrMax) {
                arrMax = arr[i];
            }
        }
        return arrMax;
    }

    // 求最小值
    public static int getMin(int[] arr) {

        int arrMin = arr[0];
        for (int i = 0; i < arr.length; i++) {

            //判断最小值
            if (arr[i] < arrMin && arr[i] != 0) {
                arrMin = arr[i];
            }
        }
        return arrMin;

    }

    //判断是否存在该值
    public static int compareArr(int[] arr, int x) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == x) {
                return 1;
            }
        }
        return 0;
    }

    public static String toZcd(String s) {
        int[] week_nums = StringUtil.SelectNumber(s);
        boolean dx_2 = true, dx_1 = true;
        for (int j = 0; j < week_nums.length - 1; j++) {
            if (!(week_nums[j + 1] - week_nums[j] == 2))
                dx_2 = false;
            if (!(week_nums[j + 1] - week_nums[j] == 1))
                dx_1 = false;
        }
        if (dx_1) {
            s = week_nums[0] + "-" + week_nums[week_nums.length - 1] + "周";
        } else if (dx_2 && week_nums[0] % 2 == 0) {
            s = week_nums[0] + "-" + week_nums[week_nums.length - 1] + "周（双）";
        } else if (dx_2) {
            s = week_nums[0] + "-" + week_nums[week_nums.length - 1] + "周（单）";
        } else s = s + "周";
        return s;
    }

    public static String[] ListToArray(List<String> list) {
        String[] arr = list.toArray(new String[list.size()]);
        return arr;
    }


    /**
     * 判断字符串是否为空 长度是否合法
     */
    public static boolean isEmpty(String str, int len) {
        return null == str || str.isEmpty() || str.length() < len || "".equals(str);
    }

    /**
     * 判断多个字符串是否为空 长度是否合法
     */
    public static boolean isEmpty(int len, String... str) {
        for (String s : str) {
            if (null == str || "".equals(str) || s.isEmpty() || s.length() < len)
                return true;
        }
        return false;
    }

    /**
     * 判断多个字符串是否为空
     */
    public static boolean isEmpty(String... str) {
        for (String s : str) {
            if (null == s || "".equals(s) || s.isEmpty() )
                return true;
        }
        return false;
    }

    /**
     * 判断字符串是否为空
     */
    public static boolean isEmpty(String str) {
        return null == str || "".equals(str) || str.isEmpty();
    }

    /**
     * object是否为空
     */
    public static boolean isEmpty(Object obj) {
        return null == obj;
    }


    /**
     * 检测邮箱地址是否合法
     *
     * @param email
     * @return true合法 false不合法
     */
    public static boolean isEmail(String email) {
        if (isEmpty(email)) return false;
        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配
        Matcher m = p.matcher(email);
        return m.matches();
    }

    public static boolean verifyCodeEquals(String verifyCode, String userCode) {
        if (isEmpty(verifyCode) || isEmpty(userCode)) return false;
        return verifyCode.toUpperCase().equals(userCode.toUpperCase());
    }

    public static String apkNameillegalCharacter(String name) {
        if (name.contains("-")) name = name.replace("-", "");
        return name;
    }

    public static boolean cookieListIsEmpty(Cookie[] cookieList) {
        return cookieList == null || cookieList.length == 0;
    }

    public static boolean cookiesIsEmpty(Map<String, String> cookies) {
        return cookies == null || cookies.size() == 0;
    }

    public static String rmBadParame(String param) {
        return param.replace(" ", "").replace("\n", "").replace("\t", "").replace("\r", "");
    }

    public static boolean checkResult(JSONObject jsonObject) {
        return jsonObject != null && jsonObject.containsKey("result") && jsonObject.getBooleanValue("result");
    }

    public static boolean isJson(String s) {
        return !isEmpty(s) && !s.contains("<") && s.contains("{");
    }

    public static String getMapToString(Map<String, String> map) {
        Set<String> keySet = map.keySet();
        //将set集合转换为数组
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        //给数组排序(升序)
        Arrays.sort(keyArray);
        //因为String拼接效率会很低的，所以转用StringBuilder
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keyArray.length; i++) {
            // 参数值为空，则不参与签名 这个方法trim()是去空格
            if ((String.valueOf(map.get(keyArray[i]))).trim().length() > 0) {
                sb.append(keyArray[i]).append(":").append(String.valueOf(map.get(keyArray[i])).trim());
            }
            if (i != keyArray.length - 1) {
                sb.append(";");
            }
        }
        return sb.toString();
    }

    public static String listToString(List<scoreDetails> list, char separator) {
        String string = "";
        for (scoreDetails o : list) {
            string = JSONObject.toJSONString(o);
            Log.e("scoreDetails", string);
        }
        return list.isEmpty() ? "" : string.substring(0, string.toString().length() - 1);
    }

    public static String getUserAgent(Context context) {
        String userAgent = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                userAgent = WebSettings.getDefaultUserAgent(context);
            } catch (Exception e) {
                userAgent = System.getProperty("http.agent");
            }
        } else {
            userAgent = System.getProperty("http.agent");
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }


    public static List<Consumer> removeDuplicateConsumer(List<Consumer> list) {
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = list.size() - 1; j > i; j--) {
                if (list.get(j).getTjyf().equals(list.get(i).getTjyf())) {
                    list.remove(j);
                }
            }
        }
        return list;
    }


    public static List<Borrow> removeDuplicateBorrow(List<Borrow> list) {
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = list.size() - 1; j > i; j--) {
                if (list.get(j).getBorrowTime().equals(list.get(i).getBorrowTime())) {
                    list.remove(j);
                }
            }
        }
        return list;
    }

    /**
     * 判断字符串中是否包含中文
     * @param str
     * 待校验字符串
     * @return 是否为中文
     * @warn 不能校验是否为中文标点符号
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }
}
